<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>主页</title>
  <style>
    ul {
      list-style: none;
    }

    li:hover {
      background-color: #f5f5f5;
    }
  </style>
</head>

<body>
  我是主页
  <ul id="goodsList"></ul>
  <input id="goodsID" type="text" value="" disabled />
  <input id="goodsName" type="text" value="" />
  <input id="goodsPrice" type="text" value="" />
  <button id="add">添加</button>
  <button id="edit">修改</button>
  <script>
    fetch('http://localhost:7001', {
      method: 'GET', // or 'PUT'
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('Success:', data);
        let html = '';
        goodsList.innerHTML = data.map(item => {
          return `<li id="${item.id}">
              <span data-name>${item.name}</span>
              <span>${item.price}</span>
            </li>`
        }).join('')

      })
      .catch((error) => {
        console.error('Error:', error);
      });


    add.onclick = function () {
      fetch(`http://localhost:7001/add?name=${goodsName.value}&price=${goodsPrice.value}`, {
        method: 'POST', // or 'PUT'
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then((response) => response.json())
        .then((data) => {
          console.log('Success:', data);

          goodsList.innerHTML = data.map(item => {
            return `<li id="${item.id}">
              <span>${item.name}</span>
              <span>${item.price}</span>
            </li>`
          }).join('')

        })
        .catch((error) => {
          console.error('Error:', error);
        });
    }


    // 修改
    goodsList.onclick = function (e) {
      console.log(e.target);
      goodsID.value = e.target.id;
      goodsName.value = '';
      goodsPrice.value = '';

      // fetch(`http://localhost:7001/edit?name=${goodsName.value}&price=${goodsPrice.value}`, {
      //   method: 'put', // or 'PUT'
      //   headers: {
      //     'Content-Type': 'application/json',
      //   },
      // })
      //   .then((response) => response.json())
      //   .then((data) => {
      //     console.log('Success:', data);
      //     location.reload();
      //   })
      //   .catch((error) => {
      //     console.error('Error:', error);
      //   });
    }

  </script>
</body>

</html>